// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2025-01-08

package container

import (
	"gitee.com/go-libs/perm/types"
)

type (
	// RoleContainer is a component interface that store role definitions.
	RoleContainer interface {
		// AddPermission add permission to role.
		AddPermission(typ types.Permission)

		// GetPermissions returns role permissions mapping.
		//
		//   {
		//       "user": "user",
		//       "user:add": "user:add",
		//   }
		GetPermissions() map[types.Permission]string

		// GetPermissionsValues returns role permissions values.
		//
		//   [
		//       "user",
		//       "user:add"
		//   ]
		GetPermissionsValues() []string

		// GetRole returns role type.
		GetRole() types.Role
	}

	role struct {
		Role              types.Role
		Permissions       map[types.Permission]string
		PermissionsKeys   []string
		PermissionsValues []string
	}
)

func NewRoleContainer(name types.Role) RoleContainer {
	return &role{
		Role:              name,
		Permissions:       make(map[types.Permission]string),
		PermissionsKeys:   make([]string, 0),
		PermissionsValues: make([]string, 0),
	}
}

func (o *role) AddPermission(typ types.Permission) {
	// Ignore if type is empty.
	if typ.IsEmpty() {
		return
	}

	// Skip if permission exists.
	if _, ok := o.Permissions[typ]; ok {
		return
	}

	// Update permissions mapping.
	str := typ.String()
	o.Permissions[typ] = str
	o.PermissionsKeys = append(o.PermissionsKeys, str)
	o.PermissionsValues = append(o.PermissionsValues, str)
}

func (o *role) GetPermissions() map[types.Permission]string {
	return o.Permissions
}

func (o *role) GetPermissionsValues() []string {
	return o.PermissionsValues
}

func (o *role) GetRole() types.Role {
	return o.Role
}
